﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Husb.Util;
using Husb.Util.Enum;
using CentralOffice.Archive.Data;
using CentralOffice.Archive.BusinessActions;

using CategoryTable = CentralOffice.Archive.Data.CategoryDataSet.CategoryDataTable;
using CategoryRow = CentralOffice.Archive.Data.CategoryDataSet.CategoryRow;

using ArchiveTable = CentralOffice.Archive.Data.ArchiveDataSet.ArchivesDataTable;
using ArchiveRow = CentralOffice.Archive.Data.ArchiveDataSet.ArchivesRow;

namespace CentralOffice.WebClient.Archives
{
    public partial class ArchiveEdit : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                SiteUtil.PopulateListBox(ddlSecretLevel, SiteConstants.SecretLevel, false);

                txtFiledDate.Text = DateTime.Now.ToString("yyyy-MM-dd");

                string archiveId = HttpContext.Current.Request.QueryString["id"];
                if (String.IsNullOrEmpty(archiveId))
                {
                    txtFiledDate.Text = DateTime.Now.ToString();
                    txtFiledDate.Enabled = false;

                    txtOrderNumber.Text = (Archive.BusinessActions.Archive.GetMaxOrderNumber() + 1).ToString();
                }
                else
                {
                    SetFields(archiveId);
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Guid archiveId = this.Save();
            ClearFields();
            Response.Redirect("ArchiveView.aspx?id=" + archiveId.ToString());
            //lblJavaScript.Text = "<script type=\"text/javascript\">window.open('DepartmentAdd.aspx');</script>";
        }

        protected void btnContinue_Click(object sender, EventArgs e)
        {
            this.Save();
            ClearFields();
        }

        private Guid Save()
        {
            string archiveId = HttpContext.Current.Request.QueryString["id"];
            //String savePath = SiteUtil.GetDocumentFilePath();
            ArchiveDataSet archives = GetFields(archiveId);
            int cnt = CentralOffice.Archive.BusinessActions.Archive.Update(archives);

            //SaveFile(savePath);

            return (archives.Archives.Rows[0] as ArchiveRow).Id;
        }

        private void SetFields(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                ArchiveRow archive = CentralOffice.Archive.BusinessActions.Archive.GetById(new Guid(id));

                txtName.Text = archive.Name;
                //txtNoticeNumber.Text = notice.NoticeNumber;
                //txtQueryNumber.Text = notice.QueryNumber;
                //if (!archive.IsUrgencyPriorityNull())
                //{
                //    ddlUrgencyPriority.SelectedValue = EnumUtil.GetInt32(SiteConstants.Priority, CategoryDataSourceType.Xml, archive.UrgencyPriority).ToString();
                //}
                if (!archive.IsCategoryNull())
                {
                    ddlCategory.SelectedValue = archive.CategoryId.ToString(); //EnumUtil.GetInt32(SiteConstants.SecretLevel, CategoryDataSourceType.Xml, archive.SecretLevel).ToString();
                }

                if (!archive.IsSecretLevelNull())
                {
                    ddlSecretLevel.SelectedValue = EnumUtil.GetInt32(SiteConstants.SecretLevel, CategoryDataSourceType.Xml, archive.SecretLevel).ToString();
                }

                //txtSubtitle.Text = archive.IsSubtitleNull() ? "" : archive.Subtitle;
                //txtFileNumber.Text = archive.IsFileNumberNull() ? "" : archive.FileNumber;
                //txtKeywords.Text = archive.IsKeywordsNull() ? "" : archive.Keywords;
                //txtTheme.Text = archive.IsThemeNull() ? "" : archive.Theme;

                //txtPublisher.Text = archive.IsPublisherNull() ? "" : archive.Publisher;

                ////txtFileCategoryId.Text = archive.FileCategoryId;
                //txtRemark.Text = archive.IsRemarkNull() ? "" : archive.Remark;
                //txtArchivingTime.Text = archive.ArchivingTime.ToString();
                //txtArchivedBy.Text = archive.ArchivedBy;
                //txtDepositIn.Text = archive.IsDepositInNull() ? "" : archive.DepositIn;

                txtCustomer.Text = archive.Customer;
                //txtQueryNumber.Text = archive.QueryNumber;
                txtAddress.Text = archive.Address;
                txtTelephone1.Text = archive.Telephone1;
                //txtTelephone2.Text = archive.Telephone2;
                //txtFax.Text = archive.Fax;
                //txtEmail.Text = archive.Email;
                txtContact.Text = archive.Contact;
                //txtContactTitle.Text = archive.ContactTitle;
                //txtContactPhone.Text = archive.ContactPhone;


                txtName.Text = archive.Name;
                txtOrderNumber.Text = archive.OrderNumber.ToString();
                //txtQueryNumber.Text = archive.QueryNumber;
                txtProvince.Value = archive.Province;
                txtCity.Value = archive.City;
                //txtCounty.Text = archive.County;
                txtContractCode.Text = archive.ContractCode;
                txtFiledDate.Text = archive.FiledDate.ToString("yyyy-MM-dd");
                //txtCustomerId.Text = archive.CustomerId;
                //txtCategoryId.Text = archive.CategoryId;
                if (!archive.IsScaleNull())
                {
                    txtScale.Text = archive.Scale.ToString();
                }
                txtConstructForm.Text = archive.ConstructForm;
                txtDesignStage.Text = archive.DesignStage;
                txtBelongedTo.Text = archive.BelongedTo;
                txtProjectManager.Text = archive.ProjectManager;

                txtExecutor.Value = archive.IsExecutorNull() ? "" : archive.Executor;
                txtExecutorReadOnly.Value = txtExecutor.Value;


                //txtBuildingBlueprint.Text = archive.BuildingBlueprint;
                //txtElectricalBlueprint.Text = archive.ElectricalBlueprint;
                //txtMechanicalMaterialManifest.Text = archive.MechanicalMaterialManifest;
                //txtElectricalMaterialManifest.Text = archive.ElectricalMaterialManifest;
                //txtSystemSolution.Text = archive.SystemSolution;
                //txtElectricalSolution.Text = archive.ElectricalSolution;

                //lblBuildingBlueprint.Text = "<br />" + archive.BuildingBlueprint;
                //lblElectricalBlueprint.Text = "<br />" + archive.ElectricalBlueprint;
                //lblMechanicalMaterialManifest.Text = "<br />" + archive.MechanicalMaterialManifest;
                //lblElectricalMaterialManifest.Text = "<br />" + archive.ElectricalMaterialManifest;
                //lblSystemSolution.Text = "<br />" + archive.SystemSolution;
                //lblElectricalSolution.Text = "<br />" + archive.ElectricalSolution;

                if (!archive.IsBuildingBlueprintNull() && archive.BuildingBlueprint.Length > 0)
                {
                    lblBuildingBlueprint.Text = "<br />" + archive.BuildingBlueprint.Substring(archive.BuildingBlueprint.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    //lblBuildingBlueprint.NavigateUrl = archive.BuildingBlueprint;
                    lblBuildingBlueprint.Visible = true;
                }


                if (!archive.IsElectricalBlueprintNull() && archive.ElectricalBlueprint.Length > 0)
                {
                    lblElectricalBlueprint.Text = "<br />" + archive.ElectricalBlueprint.Substring(archive.ElectricalBlueprint.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    //lblElectricalBlueprint.NavigateUrl = archive.ElectricalBlueprint;
                    lblElectricalBlueprint.Visible = true;
                }

                if (!archive.IsMechanicalMaterialManifestNull() && archive.MechanicalMaterialManifest.Length > 0)
                {
                    lblMechanicalMaterialManifest.Text = "<br />" + archive.MechanicalMaterialManifest.Substring(archive.MechanicalMaterialManifest.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    //lblMechanicalMaterialManifest.NavigateUrl = archive.MechanicalMaterialManifest;
                    lblMechanicalMaterialManifest.Visible = true;
                }

                if (!archive.IsElectricalMaterialManifestNull() && archive.ElectricalMaterialManifest.Length > 0)
                {
                    lblElectricalMaterialManifest.Text = "<br />" + archive.ElectricalMaterialManifest.Substring(archive.ElectricalMaterialManifest.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    //lblElectricalMaterialManifest.NavigateUrl = archive.ElectricalMaterialManifest;
                    lblElectricalMaterialManifest.Visible = true;
                }

                if (!archive.IsSystemSolutionNull() && archive.SystemSolution.Length > 0)
                {
                    lblSystemSolution.Text = "<br />" + archive.SystemSolution.Substring(archive.SystemSolution.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    //lblSystemSolution.NavigateUrl = archive.SystemSolution;
                    lblSystemSolution.Visible = true;
                }

                if (!archive.IsElectricalSolutionNull() && archive.ElectricalSolution.Length > 0)
                {
                    lblElectricalSolution.Text = "<br />" + archive.ElectricalSolution.Substring(archive.ElectricalSolution.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    //lblElectricalSolution.NavigateUrl = archive.ElectricalSolution;
                    lblElectricalSolution.Visible = true;
                }

                if (!archive.IsDesignSketchNull() && archive.DesignSketch.Length > 0)
                {
                    lblDesignSketch.Text = "<br />" + archive.DesignSketch.Substring(archive.DesignSketch.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    lblDesignSketch.Visible = true;
                }

                if (!archive.IsTenderDocumentationNull() && archive.TenderDocumentation.Length > 0)
                {
                    lblTenderDocumentation.Text = "<br />" + archive.TenderDocumentation.Substring(archive.TenderDocumentation.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    lblTenderDocumentation.Visible = true;
                }

                if (!archive.IsPreliminaryDesignNull() && archive.PreliminaryDesign.Length > 0)
                {
                    lblPreliminaryDesign.Text = "<br />" + archive.PreliminaryDesign.Substring(archive.PreliminaryDesign.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    lblPreliminaryDesign.Visible = true;
                }

                if (!archive.IsOtherDocumentationNull() && archive.OtherDocumentation.Length > 0)
                {
                    lblOtherDocumentation.Text = "<br />" + archive.OtherDocumentation.Substring(archive.OtherDocumentation.LastIndexOf(System.IO.Path.AltDirectorySeparatorChar) + 1);
                    lblOtherDocumentation.Visible = true;
                }

            }
        }

        private ArchiveDataSet GetFields(string id)
        {
            ArchiveRow archive = null;

            if (String.IsNullOrEmpty(id))
            {
                archive = (new ArchiveDataSet()).Archives.NewArchivesRow();
                SiteUtil.PopulateCommonField(archive, Guid.NewGuid());
                archive.FiledDate = DateTime.Now;

                archive.CustomerId = Guid.NewGuid();
            }
            else
            {
                // update
                archive = CentralOffice.Archive.BusinessActions.Archive.GetById(new Guid(id));
            }
            archive.Name = txtName.Text;
            archive.OrderNumber = txtOrderNumber.Text.Length > 0 ? Int32.Parse(txtOrderNumber.Text):0 ;
            //archive.ContractCode = txtCode.Text;
            archive.QueryNumber = txtCode.Text;// CommonUtil.GetChineseSpell(txtName.Text);
            archive.SecretLevel = ddlSecretLevel.SelectedItem.Text;
            archive.Province = txtProvince.Value;
            archive.City = txtCity.Value;
            archive.KeyWords = txtKeyWords.Text.Trim();
            archive.DesignedYear = txtDesignedYear.Text.Trim();
            //archive.County = txtCounty.Text;
            archive.ContractCode = txtContractCode.Text;
            if (txtFiledDate.Text.Length > 0)
            {
                archive.FiledDate = DateTime.Parse(txtFiledDate.Text);
            }
            //archive.CustomerId = txtCustomerId.Text;
            archive.CategoryId = new Guid(ddlCategory.SelectedValue);
            if (txtScale.Text.Length > 0)
            {
                archive.Scale = CommonUtil.IsInteger(txtScale.Text) ? Int32.Parse(txtScale.Text) : -1;
            }
            archive.ConstructForm = txtConstructForm.Text;
            archive.DesignStage = txtDesignStage.Text;
            archive.BelongedTo = txtBelongedTo.Text;
            archive.ProjectManager = txtProjectManager.Text;

            archive.Executor = txtExecutor.Value;

            string fileName = SaveFile(SiteUtil.GetBuildingBlueprintPath(),  fileBuildingBlueprint);
            if (fileName.Length > 0)
            {
                archive.BuildingBlueprint = fileName;
            }
            fileName = SaveFile(SiteUtil.GetElectricalBlueprintPath(),  fileElectricalBlueprint);
            if (fileName.Length > 0)
            {
                archive.ElectricalBlueprint = fileName;
            }

            fileName =  SaveFile(SiteUtil.GetMechanicalMaterialManifestPath(),  fileMechanicalMaterialManifest);
            if (fileName.Length > 0)
            {
                archive.MechanicalMaterialManifest = fileName;
            }

            fileName = SaveFile(SiteUtil.GetElectricalMaterialManifestPath(),  fileElectricalMaterialManifest);
            if (fileName.Length > 0)
            {
                archive.ElectricalMaterialManifest = fileName;
            }

            fileName = SaveFile(SiteUtil.GetSystemSolutionPath(),  fileSystemSolution);
            if (fileName.Length > 0)
            {
                archive.SystemSolution = fileName;
            }

            fileName = SaveFile(SiteUtil.GetElectricalSolutionPath(), fileElectricalSolution);
            if (fileName.Length > 0)
            {
                archive.ElectricalSolution = fileName;
            }

            fileName = SaveFile(SiteUtil.GetDesignSketchPath(), fileDesignSketch);
            if (fileName.Length > 0)
            {
                archive.DesignSketch = fileName;
            }
            fileName = SaveFile(SiteUtil.GetTenderDocumentationPath(), fileTenderDocumentation);
            if (fileName.Length > 0)
            {
                archive.TenderDocumentation = fileName;
            }
            fileName = SaveFile(SiteUtil.GetPreliminaryDesignPath(), filePreliminaryDesign);
            if (fileName.Length > 0)
            {
                archive.PreliminaryDesign = fileName;
            }
            fileName = SaveFile(SiteUtil.GetOtherDocumentationPath(), fileOtherDocumentation);
            if (fileName.Length > 0)
            {
                archive.OtherDocumentation = fileName;
            }

            archive.Customer = txtCustomer.Text;
            //archive.QueryNumber = txtQueryNumber.Text;
            archive.Address = txtAddress.Text;
            archive.Telephone1 = txtTelephone1.Text;
            //archive.Telephone2 = txtTelephone2.Text;
            //archive.Fax = txtFax.Text;
            //archive.Email = txtEmail.Text;
            archive.Contact = txtContact.Text;
            //archive.ContactTitle = txtContactTitle.Text;
            //archive.ContactPhone = txtContactPhone.Text;
            
            if (String.IsNullOrEmpty(id))
            {
                archive.Table.Rows.Add(archive);
            }

            string s = SiteUtil.ColumnInRow<string>(archive, "DepositIn", "");

            int? i = SiteUtil.ColumnInRow<int?>(archive, "Version", null);

            return archive.Table.DataSet as ArchiveDataSet;
        }


        private string SaveFile(string rootDir, FileUpload file)
        {
            //bool success = false;
            //String savePath = SiteUtil.GetNoticesFilePath(); //Server.MapPath("~/") + "UploadFiles/";
            string fileName = "";

            string path = Server.MapPath(rootDir);
            if (file.HasFile)
            {

                var fn = SiteUtil.GetUploadFileName(path, file.FileName);
                //fn = fn.Substring(fn.LastIndexOf('\\') + 1);
                file.SaveAs(fn);

                fileName = rootDir + fn.Substring(fn.LastIndexOf('\\') + 1);

                //file.SaveAs(path + file.FileName);
               
                //success = true;
                //fileName = rootDir + file.FileName;
            }
            else
            {
                //Page.Response.Write("fff");
            }
            //return success;
            return fileName;
        }

        private void ClearFields()
        {
            txtName.Text = "";
            //txtNoticeNumber.Text = notice.NoticeNumber;
            //txtQueryNumber.Text = notice.QueryNumber;
            //if (!archive.IsUrgencyPriorityNull())
            //{
            //    ddlUrgencyPriority.SelectedValue = EnumUtil.GetInt32(SiteConstants.Priority, CategoryDataSourceType.Xml, archive.UrgencyPriority).ToString();
            //}
            //if (!archive.IsCategoryIdNull())
            //{
            //    ddlSecretLevel.SelectedValue = archive.CategoryId.ToString(); //EnumUtil.GetInt32(SiteConstants.SecretLevel, CategoryDataSourceType.Xml, archive.SecretLevel).ToString();
            //}

            //txtSubtitle.Text = archive.IsSubtitleNull() ? "" : archive.Subtitle;
            //txtFileNumber.Text = archive.IsFileNumberNull() ? "" : archive.FileNumber;
            //txtKeywords.Text = archive.IsKeywordsNull() ? "" : archive.Keywords;
            //txtTheme.Text = archive.IsThemeNull() ? "" : archive.Theme;

            //txtPublisher.Text = archive.IsPublisherNull() ? "" : archive.Publisher;

            ////txtFileCategoryId.Text = archive.FileCategoryId;
            //txtRemark.Text = archive.IsRemarkNull() ? "" : archive.Remark;
            //txtArchivingTime.Text = archive.ArchivingTime.ToString();
            //txtArchivedBy.Text = archive.ArchivedBy;
            //txtDepositIn.Text = archive.IsDepositInNull() ? "" : archive.DepositIn;

            txtCustomer.Text = "";
            //txtQueryNumber.Text = archive.QueryNumber;
            txtAddress.Text = "";
            txtTelephone1.Text = "";
            //txtTelephone2.Text = archive.Telephone2;
            //txtFax.Text = archive.Fax;
            //txtEmail.Text = archive.Email;
            txtContact.Text = "";
            //txtContactTitle.Text = archive.ContactTitle;
            //txtContactPhone.Text = archive.ContactPhone;


            txtName.Text = "";
            //txtQueryNumber.Text = archive.QueryNumber;
            txtProvince.Value = "";
            txtCity.Value = "";
            //txtCounty.Text = archive.County;
            txtContractCode.Text = "";
            txtFiledDate.Text = "";
            //txtCustomerId.Text = archive.CustomerId;
            //txtCategoryId.Text = archive.CategoryId;
            txtScale.Text = "";
            txtConstructForm.Text = "";
            txtDesignStage.Text = "";
            txtBelongedTo.Text = "";
            txtProjectManager.Text = "";
            

            lblBuildingBlueprint.Text = "";
            lblElectricalBlueprint.Text = "";
            lblMechanicalMaterialManifest.Text = "";
            lblElectricalMaterialManifest.Text = "";
            lblSystemSolution.Text = "";
            lblElectricalSolution.Text = "";

            lblDesignSketch.Text = "";
            lblTenderDocumentation.Text = "";
            lblPreliminaryDesign.Text = "";
            lblOtherDocumentation.Text = "";
        }


        protected void tvEmp_Load(object sender, EventArgs e)
        {
            this.tvEmp.Attributes.Add("OnClick", "OnTreeNodeChecked(event)");
        }

        protected void btnShowPopup_Click(object sender, EventArgs e)
        {
            string[] assignedBy = null;
            LinkButton btn = sender as LinkButton;
            if (btn != null)
            {
                txtSelectedObject.Value = btn.CommandName;

                if (btn.CommandName == "Executor")
                {
                    assignedBy = txtExecutor.Value.Split(',');
                }
                else
                {
                    //assignedBy = txtApprovedBy.Value.Split(',');
                }
            }

            tvEmp.Nodes.Clear();
            HumanResources.HumanResourcesHelper.PopulateEmployeeTree(tvEmp, true, assignedBy);//null 

            updPnlDepartment.Update();
            mdlDetailView.Show();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            // 保存弹出窗口所更新的信息
            string employees = "";
            string employeesId = "";

            if (tvEmp.CheckedNodes.Count > 0)
            {
                foreach (TreeNode node in tvEmp.CheckedNodes)
                {
                    if (!node.Text.StartsWith("["))
                    {
                        employees += node.Text + ",";
                        employeesId += node.Value + ",";
                    }
                }
            }
            if (txtSelectedObject.Value == "Executor")
            {
                //txtApplicantReadOnly.Value = employees.Trim(',');
                txtExecutorReadOnly.Value = employees.Trim(',');
                txtExecutor.Value = employees.Trim(',');
            }
            else
            {
                //txtApprovedByReadOnly.Value = employees.Trim(',');
                //txtApprovedBy.Value = departmentsId;
                //txtApprovedBy.Value = employees.Trim(',');
            }
        }
    }
}